package com.fishingwithme.infrastructure;

import com.fishingwithme.domain.user.SpotUser;
import com.fishingwithme.domain.user.UserService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service
class UserDetailsServiceImpl implements UserDetailsService {
    private final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {


      SpotUser  user = null;
        try{
            Long id = Long.valueOf(username);
            user  = userService.loadUserByUserId(id);
        }catch(Exception e) {
            log.warn("load user by id failed ,now going to load user by username", e);
             throw new UsernameNotFoundException("User Not Found with username: " + username);
        }
        if(user == null) {
             throw new UsernameNotFoundException("User Not Found with username: " + username);
        }
        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        if (user.isAdmin()) {
            authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        }

        return new FwmUserDetails(user.getUserId(),
                user.getUserId() + "",
                "", // 微信登录不使用密码
                authorities,
                user.getAvatarUrl(),
                user.getNickname()

        );
    }
}
